<?php
namespace app\index\controller;

use think\Controller;
use think\Db;
use app\index\model\Member;
use app\index\model\OrderProfit;
use app\index\model\Recharge;
use app\index\model\Getcash;
use app\index\model\Putlog;
use app\index\model\Order;
use app\index\model\Batchpay;
use app\firm\model\ProjectUser;
use app\firm\model\MoneyReturn;
use app\firm\model\MoneyReturns;
use app\firm\model\Project;
use app\firm\model\Notice;
use app\firm\model\MoneyCom;
use app\firm\model\ProjectBank;
use app\firm\model\Order as OrderModel;
use app\index\model\Comrecharge;
use app\index\model\Partner;
use app\admin\model\OrderPayment;
use app\admin\model\ApplicationForMoney;
use redis\Redis;
use expand\Yunst;

class Backcall extends Common
{
	private $cModel;
	private $YunClass;
	public $param;
	private $puModel;
	private $mrsModel;

    public function _initialize(){
        parent::_initialize();
		$this->YunClass = new Yunst();
		$this->cModel = new Member();
		$this->puModel = new ProjectUser();
		$this->mrsModel = new MoneyReturns();
		$this->param = input('param.');
		//$this->param = unserialize(file_get_contents('BACK.txt'));
		if(!$this->YunClass->CheckSign($this->param)){
			//file_put_contents('1.txt',serialize($this->param).PHP_EOL,FILE_APPEND);
			return ajaxReturn('sign is error');
		}
		file_put_contents('130.txt',serialize($this->param).PHP_EOL,FILE_APPEND);
    }
	//会员签约编号
	public function Qianyue(){
		$rps = $this->param['rps'];
		$rps = htmlspecialchars_decode($rps);
		$rps = json_decode($rps,true);
		if($rps['status'] == 'OK'){
			$bizUserId = $rps['returnValue']['bizUserId'];
			$ContractNo = $rps['contractNo'];
			$this->cModel->where(['bizUserId'=>$bizUserId])->update(['signContract'=>$ContractNo]);
		}
	}

	//企业会员签约编号
	public function QyQianYue() {
		$rps = $this->param['rps'];
		$rps = htmlspecialchars_decode($rps);
		file_put_contents(date("Y-m-d H", time()) . 'qy_qianyue.txt', $rps . PHP_EOL, FILE_APPEND);
		$rps = json_decode($rps, true);
		if ($rps['status'] == 'OK') {
			$bizUserId = $rps['returnValue']['bizUserId'];
			$this->puModel->where(['bizUserId' => $bizUserId])->update(['is_sign' => 1]);
			$projectuser_info = $this->puModel->where(array('bizUserId' => $bizUserId))->find();
			$projectuser_info = empty($projectuser_info)?array():$projectuser_info->toArray();
			$redis = Redis::instance();
			$token = $redis->get('user:' . $projectuser_info['id']);
			$firm_info = json_decode($redis->hGet('firm_info' , $token) ,true);
			$firm_info['modify'] = true;
			$redis->hSet('firm_info', $token, json_encode($firm_info));
			ajaxReturn('success', 1);
		}
	}

	/*
 * 企业充值回调
 * @author cpy(1442435897@qq.com)
 * @return \think\response\Json
 */

	public function rechargeReturn() {
		$rps = $this->param['rps'];
		$rps = htmlspecialchars_decode($rps);
                $rag = $rps;
		$rps = json_decode($rps, true);
		$returnValue = $rps['returnValue'];
                file_put_contents('qiyePay.txt', date('Y-m-d H:i:s').PHP_EOL.$rag . PHP_EOL, FILE_APPEND);
		$moneyCom = new MoneyCom();
		$redis = Redis::instance();
        $where['order_num'] = ['eq', $returnValue['bizOrderNo']];
        $info = $moneyCom->getInfo($where);
        if(empty($info)){
            return ajaxReturn('order is null');
        }
        if($info['status']==2){
            return ajaxReturn('order is not status');
        }
		if ($rps['status'] == 'OK') {
			Db::startTrans();
			try {

				$row = $moneyCom->save(['status' => 2], ['order_num' => $returnValue['bizOrderNo']]);
                                $user = $this->puModel->getUserInfo(['id' => $info['company_id']]);
				$res = $this->puModel->where('id', $info['company_id'])->update(['money' => $user['money'] + $info['money']]);
				if ($row && $res) {
					Db::commit();
					$redis = Redis::instance();
					$token = $redis->get('user:' . $info['company_id']);
					$firm_info = json_decode($redis->hGet('firm_info' , $token) ,true);
					$firm_info['modify'] = true;
					$redis->hSet('firm_info', $token, json_encode($firm_info));
				 ajaxReturn('success', 1);
				} else {
				 ajaxReturn('error');
				}
			} catch (\Exception $e) {
				Db::rollback();
				return $e;
			}
		} else {
			$moneyCom->save(['status' => 3], ['order_num' => $returnValue['bizOrderNo']]);
		}
	}

	//充值结果通知
	public function recharge(){
		$rps = $this->param['rps'];
		$rps = htmlspecialchars_decode($rps);
		file_put_contents(date("Y-m-d H", time()) . 'test_charge.txt', $rps . PHP_EOL, FILE_APPEND);
		$rps = json_decode($rps,true);

		$RecModel = new Recharge();
		$returnValue = $rps['returnValue'];

		$orderInfo = $RecModel->where(['order'=>$returnValue['bizOrderNo'],'orderNo'=>$returnValue['orderNo']])->find();
		if(empty($orderInfo)){
			return ajaxReturn('order is null');
		}
        if($orderInfo['status']!=1){
            return ajaxReturn('order is not status');
        }
		if($rps['status'] == 'error'){
			$RecModel->where(['id'=>$orderInfo['id']])->update(['status'=>0]);
			return ajaxReturn('pay error');
		}
		if($rps['status'] == 'OK'){
			if($orderInfo['status'] == 2){
				return ajaxReturn('double pay');
			}
			$RecModel->where(['id'=>$orderInfo['id']])->update(['status'=>2]);
			$userId = $orderInfo['user_id'];
			$MemberInfo = $this->cModel->where(['id'=>$userId])->find();
			if(empty($MemberInfo)){
				return ajaxReturn('member is null');
			}
			$amount = $orderInfo['money']; //扣手续费
			$money = $MemberInfo['money'] + $amount;
			$res = $this->cModel->where(['id'=>$userId])->update(['money'=>$money]);
			if($res){
				$logModel = new Putlog();
				$log = [
					'uid' => $userId,
					'money' => $amount,
					'type'	=> 2,
					'order'	=> 'OD'.create_order(),
					'status' => 1,
					'crate_time' => time()
				];
				$logModel->allowField(true)->save($log);
				TobeNotice2($userId,'充值通知','充值金额￥'.$amount.'已到账');
				return ajaxReturn('success',1);
			}
		}
	}


	//提现回调
	public function getcash(){
		$rps = $this->param['rps'];
		$rps = htmlspecialchars_decode($rps);
		$rps = json_decode($rps,true);

		$cashModel = new Getcash();
		$returnValue = $rps['returnValue'];

		$orderInfo = $cashModel->where(['order'=>$returnValue['bizOrderNo']])->find();
		if(empty($orderInfo)){
			return ajaxReturn('order is null');
		}
		if($orderInfo['status']==2){
			return ajaxReturn('order is not status');
		}
		if($rps['status'] == 'error'){
			$cashModel->where(['id'=>$orderInfo['id']])->update(['status'=>3]);
			$res = $this->cModel->where(['id'=>$orderInfo['user_id']])->setInc('money', $orderInfo['money']);
			if($res){
				$logModel = new Putlog();
				$log = [
					'uid' => $orderInfo['user_id'],
					'money' => $orderInfo['money'],
					'type'	=> 3, //退还
					'order'	=> 'OD'.create_order(),
					'status' => 1,
					'crate_time' => time()
				];
				$logModel->allowField(true)->save($log);
				TobeNotice2($orderInfo['user_id'],'提现通知',$rps['message']);
			}
			return ajaxReturn('pay error');
		}
		if($rps['status'] == 'OK'){
			$cashModel->where(['id'=>$orderInfo['id']])->update(['status'=>2]);
			TobeNotice2($orderInfo['user_id'],'提现通知','提现成功入账!');
			return ajaxReturn('success',1);
		}
	}


    /*
   * 企业回款代收回调
   * @author cpy(1442435897@qq.com)
   * @return \think\response\Json
   */

  public function payBackReturn() {
        $rps = $this->param['rps'];
        $rps = htmlspecialchars_decode($rps);
        $rps = json_decode($rps, true);
        $returnValue = $rps['returnValue'];
        $rps['date'] = date('Y-m-d H:i:s');
        file_put_contents('qiyedaishou.txt', json_encode($rps).PHP_EOL, FILE_APPEND);
        $monReturn = new MoneyReturn();
        $monReturns = new MoneyReturns();
        $orderModel = new OrderModel();
        $notice = new Notice();
        $project = new Project();

        $info = $monReturn->getJoinInfo(['order_no' => $returnValue['bizOrderNo']],'a.*,b.project_name');
        if (empty($info)) {
            return ajaxReturn('order is null');
        }
      if($info['status']==2){
          return ajaxReturn('order is not status');
      }
        if ($rps['status'] == 'OK') {
            Db::startTrans();
            try {
                $row = $monReturn->save(['status' => 2], ['id' => $info['id']]);
                $datas = [
                    'uid' => $info['company_id'],
                    'title' => '回款',
                    'content' => '您好,企业家,您于' . date('Y-m-d H:i:s') . '成功完成项目<' . $info['project_name'] . '>的回款操作,回款金额' . $info['money'] . '元,如有疑问,欢迎致电400-605-9006',
                    'type' => 2
                ];
                $tag = $notice->save($datas);
                if ($row && $tag) {
                    Db::commit();
                    $pwhere['id'] = ['eq', $info['project_id']];
                    $pMoney = $project->getInfo($pwhere, 'target_code,basic_code');
//                    $scale = sprintf("%.2f",substr(sprintf("%.10f", $info['money'] / ($pMoney['target_code']-$pMoney['basic_code'])), 0, -2));
					$scale= sprintf("%.10f",$info['money'] / ($pMoney['target_code']-$pMoney['basic_code']));
                    $where['project_id'] =$info['project_id'];
					$where['status'] = 2;
					$where['type'] = 1;
                    $res = $orderModel->selectInfo($where);
                    foreach ($res as $k => $v) {
                        $data[] = [
                            'return_id' => $info['id'],
                            'company_id' => $info['company_id'],
                            'order_id' => $v['id'],
                            'uid' => $v['uid'],
                            'project_id' => $v['project_id'],
                            'money_profit' => sprintf("%.2f",$scale),
                            'money' => floor(floor($v['money']) * $scale),
//                            'money' => sprintf("%.2f", $v['money'] * $scale),
                            'remarks' => $info['remarks'],
                        ];
//                        $res = $monReturns->isUpdate(false)->save($data);
//                        if(!$res){
//                            file_put_contents('payback_returns'.date('Y-m-d H').'.txt',json_encode($data).PHP_EOL,FILE_APPEND);
//                        }
                    }
                    $res = $monReturns->isUpdate(false)->saveAll($data);
                    if($res){
                        return ajaxReturn('success', 1);
                    }else{
                        return ajaxReturn('error');
                    }
                } else {
                    return ajaxReturn('error');
                }
            } catch (\Exception $e) {
                Db::rollback();
                return $e->getMessage();
            }
        } else {
            //$this->puModel->where(['id' => $info['company_id']])->setInc('money', $info['money']);
        }
        return ajaxReturn('success', 1);
    }

    //代收回调
	public function apply(){
		$rps = $this->param['rps'];
		$rps = htmlspecialchars_decode($rps);
		file_put_contents(date("Y-m-d H", time()).'back_new_test3.txt',$rps.PHP_EOL,FILE_APPEND);
        $rps = json_decode($rps,true);
		$orderModel = new Order();
		$returnValue = $rps['returnValue'];

		$orderInfo = $orderModel->where(['order_sn'=>$returnValue['bizOrderNo']])->find();
		if(empty($orderInfo)){
			return ajaxReturn('order is null');
		}
		if($orderInfo['status']==2){
			return ajaxReturn('pay again');
		}
		if($rps['status'] == 'OK'){
			//扣款
			$res = $this->cModel->where(['id'=>$orderInfo['uid']])->setDec('money', $orderInfo['money']);
			if($res){
				//添加消费记录
				$putModel = new Putlog();
				$log = [
					'order' => 'OD'.create_order(),
					'uid' => $orderInfo['uid'],
					'money'	=> -$orderInfo['money'],
					'type'	=> 1,
					'status'	=> 1,
					'create_time'=> time()
				];
				$logid = $putModel->allowField(true)->save($log);
				//项目状态
				$orderModel->where(['id'=>$orderInfo['id']])->update(['status'=>2]);
                $opModel = new OrderProfit();
                $mModel = new Member();
                $data = $opModel->where(['order_sn'=>$returnValue['bizOrderNo']])->find();
                if ($data) {
                    $subordinateBizUserId = $mModel->where(['id'=>$data['member_id']])->value('bizUserId');
                    $new_order = [
                        'order_sn' => $data['payment_sn'],
                        'money'	=> $data['money'],
                    ];
                    $YunClass = new Yunst();
                    $updateTime = time();
                    $new_message = $YunClass->PingTaiZhuanZhang($subordinateBizUserId,$new_order);
                    if ($new_message['status'] != 'OK') {
                        $opModel->where(['id'=>$data['id']])->update(['status'=>2,'update_time'=>$updateTime,'remark'=>$new_message['message']]);
                        return ajaxReturn($new_message['message']);
                    } else {

                        $opModel->where(['order_sn'=>$returnValue['bizOrderNo']])->update(['status'=>1,'update_time'=>$updateTime]);
                        $money = $mModel->where(['id'=>$data['member_id']])->value('money');
                        $new_money = $money + $data['money'];
                        $mModel->where(['id'=>$data['member_id']])->update(['money'=>$new_money]);
                    }
                    $memberData = $mModel->where(['id'=>$data['subordinate_member_id']])->find();
                    $str = substr_replace($memberData['mobile'],'****',3,4);
                    $namestr = $memberData['username'];  //utf-8编码的字符串
                    $name = mb_substr($namestr, 0, 1, 'utf-8').'*';
                    TobeNotice2($data['member_id'],'佣金通知','恭喜您！您手机号为'.$str.'的好友'.$name.'先生/女士认投项目'.$data['order_money'].'元人民币，恭喜您获得好友奖励'.$data['money'].'元人民币！');

                }
                TobeNotice2($orderInfo['uid'],'消费通知','支持项目,成功支付'.$orderInfo['money'].'元。');
				return ajaxReturn('success',1);
			}

        }
	}

	//代付回调
	public function signalpay(){
		$rps = $this->param['rps'];
		$rps = htmlspecialchars_decode($rps);
		$rps = json_decode($rps,true);
		//print_r($rps);
	}

	//批量代付回调
	public function batchpay(){
		$rps = $this->param['rps'];
		$rps = htmlspecialchars_decode($rps);
		$rps = json_decode($rps,true);

		if($rps['status'] != 'OK'){
			return ajaxReturn('pay error');
		}

		$orderModel = new Order();
		$batchModel = new Batchpay();
		$returnValue = $rps['returnValue'];

		$orderInfo = $batchModel->where(['bizOrderNo'=>$returnValue['bizOrderNo']])->find();
		if(empty($orderInfo)){
			return ajaxReturn('order is null');
		}
		if($orderInfo['orderNo']){
			return ajaxReturn('pay again');
		}
		$amount = $returnValue['amount'] / 100;
		//改变项目订单状态
		$orderModel->where(['project_id'=>$orderInfo['project_id'],'uid'=>$orderInfo['uid'],'status'=>1])->update(['status'=>2]);
		$batchModel->where(['id'=>$orderInfo['id']])->update(['orderNo'=>$returnValue['orderNo'],'payDate'=>$returnValue['payDatetime']]);
		//返回金额
		$res = $this->cModel->where(['id'=>$orderInfo['uid']])->setInc('money', $amount);
		if($res){
			$logModel = new Putlog();
			$log = [
				'uid' => $orderInfo['uid'],
				'money' => $amount,
				'type'	=> 3, //退还
				'order'	=> 'OD'.create_order(),
				'status' => 1,
				'crate_time' => time()
			];
			$logModel->allowField(true)->save($log);
			TobeNotice2($orderInfo['uid'],'退还通知','项目本金返还'.$amount.'元。');
		}
		return ajaxReturn('success',1);
	}

	//退款回调
	public function backorder(){

	}

	/**
	 * 项目方设置企业信息回调
	 * @author hey_heyang(635870453@qq.com)
	 */
	public function backproject() {
		$puModel = new ProjectUser();
		$rps = $this->param['rps'];
		$rps = htmlspecialchars_decode($rps);
		file_put_contents(date("Y-m-d H", time()) . 'verify_project.txt', $rps . PHP_EOL, FILE_APPEND);
		$rps = json_decode($rps, true);
		$returnValue = $rps['returnValue'];
		$bizUserId = $returnValue['bizUserId'];
		$projectuser_info = $puModel->where(array('bizUserId' => $bizUserId))->find();
		$projectuser_info = empty($projectuser_info)?array():$projectuser_info->toArray();
		$error['bizUserId'] =$bizUserId;
		if ($returnValue['result'] == 2) { //审核成功 默认绑定对公账户银行卡
			$res = $puModel->where(array('bizUserId' => $bizUserId))->update(array('status' => 5, 'tonglian_msg' => $returnValue['remark'], 'tonglian_check_time' => strtotime($returnValue['checkTime'])));
			if(!$res){
				$error['error'] ='企业资料审核回调时,更新企业账户状态时出错';
				file_put_contents(date("Y-m-d H", time()) . 'verify_project.txt', json_encode($error,JSON_UNESCAPED_UNICODE)  . PHP_EOL, FILE_APPEND);
			}
            //绑定对公账户银行卡
            $puBack = new ProjectBank();
			$bank_data['pjtuser_id'] = $projectuser_info['id'];
			$bank_data['true_name'] = $projectuser_info['company_name'];
			$bank_data['bank_num'] = $projectuser_info['base_count'];
			$bank_data['bank_name'] = $projectuser_info['base_bank_name'];
			$bank_data['trans_date'] = date('Ymd');
			$bank_data['bank_mobile'] = $projectuser_info['mobile'];
			$bank_data['type'] ='base';
			$bank_data['status'] = 'YES';
			$bank_data['create_time'] =time();
			$bank_data['card_type'] = '1';
			$res1 =$puBack->allowField(true)->save($bank_data);
			if($res1){
				companyTobeNotice($projectuser_info['id'], '企业信息审核成功', '您的企业信息审核已通过');
			}else{
				$error['error'] ='企业资料审核回调时,绑定对公账户银行卡出错';
				file_put_contents(date("Y-m-d H", time()) . 'verify_project.txt', json_encode($error,JSON_UNESCAPED_UNICODE)  . PHP_EOL, FILE_APPEND);
			}

		} elseif ($returnValue['result'] == 3) { //审核失败
			$res2 = $puModel->where(array('bizUserId' => $bizUserId))->update(array('status' => 4, 'tonglian_msg' => $returnValue['failReason'], 'tonglian_check_time' => strtotime($returnValue['checkTime'])));
			if($res2){
				companyTobeNotice($projectuser_info['id'], '企业信息审核失败', '您的企业信息审核失败，原因是:'. $returnValue['failReason']);
			}else{
				$error['error'] ='企业资料审核回调时,发送企业信息时失败';
				file_put_contents(date("Y-m-d H", time()) . 'verify_project.txt', json_encode($error,JSON_UNESCAPED_UNICODE)  . PHP_EOL, FILE_APPEND);
			}

		}
		$redis = Redis::instance();
		$token = $redis->get('user:' . $projectuser_info['id']);
		$firm_info = json_decode($redis->hGet('firm_info' , $token) ,true);
		$firm_info['modify'] = true;
		$redis->hSet('firm_info', $token, json_encode($firm_info));
		ajaxReturn('success', 1);
	}

	/**
	 * 项目批量代付回调
	 * @author hey_heyang(635870453@qq.com)
	 */
	public function orderBatchPay() {
		$rps = $this->param['rps'];
		$rps = htmlspecialchars_decode($rps);
		file_put_contents(date("Y-m-d H", time()) . 'batch_order_list.txt', $rps . PHP_EOL, FILE_APPEND);
		$rps = json_decode($rps, true);
		if ($rps['status'] != 'OK') {
			ajaxReturn('pay error');
		}

		$orderModel = new Order();
		$batchModel = new Batchpay();
		$puModel = new ProjectUser();
		$returnValue = $rps['returnValue'];
		$amount = $returnValue['amount'] / 100;
		$extendInfo = json_decode($returnValue['extendInfo'], true);
		if(empty($extendInfo['relevance_id'])){
			$error['error'] = '批量兑付回调时，扩展回参relevance_id没有值';
			file_put_contents(date("Y-m-d H", time()) . 'batch_order_list.txt', json_encode($error,JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
			ajaxReturn('扩展回参错误');
		}else{
			$relevance_id = $extendInfo['relevance_id'];
		}
		$orderInfo = $batchModel->where(['bizOrderNo' => $returnValue['bizOrderNo']])->find();
		$orderInfo = empty($orderInfo)?array():$orderInfo->toArray();
		if (empty($orderInfo)) {
			ajaxReturn('order is null');
		}
		if ($orderInfo['orderNo']) {
			ajaxReturn('pay again');
		}


		Db::startTrans();
		try{
			//改变项目订单状态
			$memberClass = new Member();
			$orderPaymentClass = new OrderPayment();
			//循环处理插入order_payment表数据
			$order_list = $orderModel->where(['project_id' => $orderInfo['project_id'], 'uid' => $orderInfo['uid'], 'status' => array('gt', 1), 'payment_status' => array('neq', 1),'relevance_id'=>$relevance_id])->select();
			$member_data = $memberClass->where(['id' => $orderInfo['uid'],])->find();
			$member_data = empty($member_data)?array():$member_data->toArray();
			$order_list = empty($order_list)?array():$order_list->toArray();
			if(empty($order_list) || empty($member_data)){
				$error['project_id'] =$orderInfo['project_id'];
				$error['uid'] =$orderInfo['uid'];
				$error['error'] = '批量代付回调时，未找到相关订单或者会员信息';
				file_put_contents(date("Y-m-d H", time()) . 'batch_order_list.txt', json_encode($error,JSON_UNESCAPED_UNICODE)  . PHP_EOL, FILE_APPEND);
				ajaxReturn('empty data');
			}
			foreach($order_list as $key=>$value){
				$payment_data = [];
				$payment_data[$key]['project_id'] = $value['project_id'];
				$payment_data[$key]['order_sn'] = $value['order_sn'];
				$payment_data[$key]['money'] = $value['money'];
				$payment_data[$key]['status'] = 2;
				$payment_data[$key]['name'] = $member_data['username'];
				$payment_data[$key]['create_time'] = $value['create_time'];
				$payment_data[$key]['mobile'] = $member_data['mobile'];
				$payment_data[$key]['payment_time'] = time();
				$payment_data[$key]['uid'] = 0;
				$payment_data[$key]['number_id'] = $member_data['certificate'];
			}
			if(!empty($payment_data)){
				$res3=$orderPaymentClass->insertAll($payment_data);
			}

			$res1=$orderModel->where(['project_id' => $orderInfo['project_id'], 'uid' => $orderInfo['uid'], 'status' => array('gt', 1), 'payment_status' => array('neq', 1),'relevance_id'=>$relevance_id])->update(['payment_status' => 1]);
			$res2=$batchModel->where(['id' => $orderInfo['id']])->update(['orderNo' => $returnValue['orderNo'], 'payDate' => $returnValue['payDatetime']]);

			//项目方余额回写
			$pModel = new Project();
			$project_info = $pModel->where(['id'=>$orderInfo['project_id']])->find();
			$project_info = empty($project_info)?array():$project_info->toArray();
			$res4=$puModel->where(['id'=>$project_info['initiator']])->setInc('money', $amount);
			$redis = Redis::instance();
			$token = $redis->get('user:' . $project_info['initiator']);
			$firm_info = json_decode($redis->hGet('firm_info' , $token) ,true);
			$firm_info['modify'] = true;
			$redis->hSet('firm_info', $token, json_encode($firm_info));
			//判断是否代付完成，完成后更新回款订单状态并发送消息
			$afmModel =new ApplicationForMoney();
			$afm_info =$afmModel->where(['id'=>$order_list[0]['relevance_id']])->find();
			$afm_info = empty($afm_info)?array():$afm_info->toArray();
			$has_daifu_money = $orderModel->where(['relevance_id'=>$order_list[0]['relevance_id'],'payment_status'=>1])->sum('money');
			if($has_daifu_money == $afm_info['real_money']){
				$afmModel->where(['id'=>$order_list[0]['relevance_id']])->update(['relevance_status'=>3]);
				companyTobeNotice($project_info['initiator'], '用款', '已入账项目投资金额' . $afm_info['real_money'] . '元。');
			}
			// 提交事务
			if ($res1 && $res2 && $res3 && $res4){
				Db::commit();
			}else{
				Db::rollback();
				$error['project_id'] =$orderInfo['project_id'];
				$error['uid'] =$orderInfo['uid'];
				$error['error'] = '批量代付回调时，更新相关信息出错';
				file_put_contents(date("Y-m-d H", time()) . 'batch_order_list.txt', json_encode($error,JSON_UNESCAPED_UNICODE)  . PHP_EOL, FILE_APPEND);
				ajaxReturn('update error');
			}
		} catch (\Exception $e) {
			// 回滚事务
			Db::rollback();
			$error['project_id'] =$orderInfo['project_id'];
			$error['uid'] =$orderInfo['uid'];
			$error['error'] = $e->getMessage();
			file_put_contents(date("Y-m-d H", time()) . 'batch_order_list.txt', json_encode($error,JSON_UNESCAPED_UNICODE)  . PHP_EOL, FILE_APPEND);
			ajaxReturn('update error');
		}
		ajaxReturn('success', 1);
	}

	/**
	 * 项目批量兑付回调
	 * @author hey_heyang(635870453@qq.com)
	 */
	public function orderDuiFuiBatchPay() {
		$rps = $this->param['rps'];
		$rps = htmlspecialchars_decode($rps);
		file_put_contents(date("Y-m-d H", time()) . 'duifu_batch_order_list.txt', $rps . PHP_EOL, FILE_APPEND);
		$rps = json_decode($rps, true);
		if ($rps['status'] != 'OK') {
			ajaxReturn('pay error');
		}

		$orderModel = new Order();
		$pModel = new \app\index\model\Project();
		$batchModel = new Batchpay();
		$memberModel = new Member();
		$returnValue = $rps['returnValue'];
		$extendInfo = json_decode($returnValue['extendInfo'], true);
		if(empty($extendInfo['mr_id'])){
			$error['error'] = '批量兑付回调时，扩展回参mr_id没有值';
			file_put_contents(date("Y-m-d H", time()) . 'duifu_batch_order_list.txt', json_encode($error,JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
			ajaxReturn('扩展回参错误');
		}else{
			$mr_id = $extendInfo['mr_id'];
		}
		$amount = $returnValue['amount'] / 100;

		$orderInfo = $batchModel->where(['bizOrderNo' => $returnValue['bizOrderNo']])->find();
		$orderInfo = empty($orderInfo)?array():$orderInfo->toArray();
		if (empty($orderInfo)) {
			ajaxReturn('order is null');
		}
		if ($orderInfo['orderNo']) {
			ajaxReturn('pay again');
		}
		Db::startTrans();
		try{
			//改变关联订单状态
//        $orderModel->where(['project_id' => $orderInfo['project_id'], 'uid' => $orderInfo['uid'], 'status' => array('gt', 1), 'payment_status' => array('neq', 1)])->update(['status' => 3]);
//			$res1=$this->mrsModel->where(['uid' => $orderInfo['uid'],'project_id'=>$orderInfo['project_id'],'status'=>1])->update(['status' => 2]);
			$res1=$this->mrsModel->where(['id' => $mr_id,'project_id'=>$orderInfo['project_id'],'status'=>1])->update(['status' => 2]);
			$res2=$batchModel->where(['id' => $orderInfo['id']])->update(['orderNo' => $returnValue['orderNo'], 'payDate' => $returnValue['payDatetime']]);
			$res = $memberModel->where(['id' => $orderInfo['uid']])->setInc('money', $amount);
			if ($res) {
				$logModel = new Putlog();
				$log = [
						'uid' => $orderInfo['uid'],
						'money' => $amount,
						'type' => 4, //回款
						'order' => 'OD' . create_order(),
						'status' => 1,
						'crate_time' => time()
				];
				$logModel->allowField(true)->save($log);
				$project_info = $pModel->where(['id'=>$orderInfo['project_id']])->find();
				$order_info = $orderModel->where(['id'=>$extendInfo['order_id']])->find();
				$true_profit = ($project_info['true_profits']*100).'%';
//				$notice = '尊敬的会员：您好！我司已针对'.$project_info['project_name'].'项目进行回款，该项目年化收益达'.$true_profit.',您本次收到回款总计'.$amount.'元。请您前往账户余额查看结算结果，谢谢支持！若有任何疑问请致电好融艺官方客服：400—605—9006';
				$notice = '尊敬的会员：您好！我司已针对'.$project_info['project_name'].'项目进行回款，该项目年化收益达'.$true_profit.',您本次收到本金'.$order_info['money'].'元+收益'.($amount-$order_info['money']).'元合计'.$amount.'元。请您前往账户余额查看结算结果，谢谢支持！若有任何疑问请致电好融艺官方客服：400—605—9006';
				TobeNotice2($orderInfo['uid'], '退还通知', $notice);
			}
			// 提交事务
			if ($res && $res1 && $res2){
				Db::commit();
			}else{
				Db::rollback();
				$error['project_id'] =$orderInfo['project_id'];
				$error['uid'] =$orderInfo['uid'];
				$error['error'] = '批量兑付回调时，更新相关信息出错';
				file_put_contents(date("Y-m-d H", time()) . 'duifu_batch_order_list.txt', json_encode($error,JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
				ajaxReturn('update error');
			}
		} catch (\Exception $e) {
			// 回滚事务
			Db::rollback();
			$error['project_id'] =$orderInfo['project_id'];
			$error['uid'] =$orderInfo['uid'];
			$error['error'] = $e->getMessage();
			file_put_contents(date("Y-m-d H", time()) . 'duifu_batch_order_list.txt', json_encode($error,JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
			ajaxReturn('update error');
		}

		ajaxReturn('success', 1);
	}

	/**
	 * 企业提现回调
	 * @author hey_heyang(635870453@qq.com)
	 */
	public function companyGetCash() {
		$rps = $this->param['rps'];
		$rps = htmlspecialchars_decode($rps);
		file_put_contents(date("Y-m-d H", time()) . 'company_get_cash.txt', $rps . PHP_EOL, FILE_APPEND);
		$rps = json_decode($rps, true);
		$cashModel = new MoneyCom();
		$returnValue = $rps['returnValue'];

		$orderInfo = $cashModel->where(['order_num' => $returnValue['bizOrderNo']])->find();
		$orderInfo = empty($orderInfo)?array():$orderInfo->toArray();
		$error['cash_id'] =$orderInfo['id'];
		$error['company_id'] =$orderInfo['company_id'];

		if (empty($orderInfo)) {
			ajaxReturn('order is null');
		}
		if ($orderInfo['status'] != 2) {
			ajaxReturn('order is not status');
		}

		if ($rps['status'] == 'error') {
			$res1 = $cashModel->where(['id' => $orderInfo['id']])->update(['status' => 4]);
			$res = $this->puModel->where(['id' => $orderInfo['company_id']])->setInc('money', $orderInfo['money']);
			if ($res && $res1) {
				$logModel = new Putlog();
				$log = [
						'uid' => $orderInfo['user_id'],
						'money' => $orderInfo['money'],
						'type' => 3, //退还
						'order' => 'OD' . create_order(),
						'status' => 1,
						'crate_time' => time(),
						'iscom' => 1,
				];
				$res2 = $logModel->allowField(true)->save($log);
				if($res2){
					companyTobeNotice($orderInfo['company_id'], '提现失败通知', $rps['message']);
				}else{
					$error['error'] ='企业端提现时,发送信息失败';
					file_put_contents(date("Y-m-d H", time()) . 'company_get_cash.txt', json_encode($error,JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
				}

			}else{
				$error['error'] ='企业端提现时,更新提现状态或者金额失败';
				file_put_contents(date("Y-m-d H", time()) . 'company_get_cash.txt', json_encode($error,JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
			}
			ajaxReturn('pay error');
		}
		if ($rps['status'] == 'OK') {
			$res4 = $cashModel->where(['id' => $orderInfo['id']])->update(['status' => 3,'order_no'=>$returnValue['orderNo']]);
			if($res4){
				companyTobeNotice($orderInfo['company_id'], '提现', '提现'.$orderInfo['money'].'元成功入账!');
			}else{
				$error['error'] ='企业端提现时,更新提现表订单号与状态失败';
				file_put_contents(date("Y-m-d H", time()) . 'company_get_cash.txt', json_encode($error,JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
			}

			ajaxReturn('success', 1);
		}
	}
}
